package com.loyalove.demo.echo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author loyal
 */
@Slf4j
public class EchoServer {

  private int port;

  public EchoServer(int port) {
    this.port = port;
  }

  public void start() throws Exception {
    /*服务器Handler*/
    final EchoServerHandler serverHandler = new EchoServerHandler();
    /*事件轮询组*/
    EventLoopGroup group = new NioEventLoopGroup();

    try {
      /*创建服务启动器*/
      ServerBootstrap sb = new ServerBootstrap();

      sb.group(group)
          .channel(NioServerSocketChannel.class)
          .localAddress(port)
          .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
              ch.pipeline().addLast(serverHandler);
            }
          });

      ChannelFuture future = sb.bind().sync();
      future.channel().closeFuture().sync();
    } finally {
      group.shutdownGracefully().sync();
    }
  }

}
